package com.ly.algorithm.offerpointer;

import java.util.Stack;

/**
 * @Classname Offer27
 * @Description
 *
 * 请完成一个函数，输入一个二叉树，该函数输出它的镜像。
 *
 * 例如输入：
 *
 *      4
 *    /   \
 *   2     7
 *  / \   / \
 * 1   3 6   9
 * 镜像输出：
 *
 *      4
 *    /   \
 *   7     2
 *  / \   / \
 * 9   6 3   1
 *
 *  
 *
 * 示例 1：
 *
 * 输入：root = [4,2,7,1,3,6,9]
 * 输出：[4,7,2,9,6,3,1]
 *
 * @Date 2021/1/27 19:28
 * @Author 冷心影翼
 */
public class Offer27 {

    public static void main(String[] args) {
        Solution27 solution27 = new Solution27();
        TreeNode treeNode = solution27.mirrorTree(TreeNode.init(new int[]{4, 2, 7, 1, 3, 6, 9}));
        TreeNode treeNode2 = solution27.mirrorTreeByStack(TreeNode.init(new int[]{4, 2, 7, 1, 3, 6, 9}));
        treeNode.preOrder(treeNode);
        System.out.println();
        treeNode2.preOrder(treeNode);
    }

}


class Solution27 {
    public TreeNode mirrorTree(TreeNode root) {
        if(root == null) {
            return null;
        }
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        mirrorTree(root.left);
        mirrorTree(root.right);
        return root;
    }

    public TreeNode mirrorTreeByStack(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while(!stack.isEmpty()) {
            TreeNode pop = stack.pop();
            TreeNode temp = pop.left;
            pop.left = pop.right;
            pop.right = temp;
            if(pop.left!=null) {
                stack.push(pop.left);
            }
            if(pop.right!=null) {
                stack.push(pop.right);
            }
        }
        return root;
    }
}